<template>
  <div class="app-container">
    <div class="header">
      <div class="word">
        <div class="w1">
          种植管理系统
        </div>
        <div class="w2">
          在种植管理系统中你可以查看种植等基本信息，同时还可以实现修改种植信息，添加种植信息等功能，提供一套可行的种植信息方案
        </div>
        <div class="w2">
          种植信息系统是种植系统中重要的一环,它可以为我们提供种植的信息，为下一步做准备
        </div>
      </div>
      <img src="../../static/u=2179590687,2836296523&fm=253&fmt=auto&app=138&f=JPEG.webp" class="imgDri">
    </div>
    <div class="index">
      <div class="searchHead">
        <el-button type="primary" @click="outerVisible = true">新增种植信息</el-button>
        <el-input v-model="searchInput" placeholder="请输入要查询的数据" class="searchIuput">
          <el-select slot="prepend" v-model="select" class="sel3" placeholder="请选择" style="width: 120px;">
            <el-option label="产品名称" value="productName" />
            <el-option label="员工名字" value="employeeName" />
            <el-option label="种植方式" value="plantMethod" />
          </el-select>
          <el-button slot="append" v-model="searchInf" icon="el-icon-search" @click="searchMes" />
        </el-input>
      </div>
      <el-dialog title="新增种植信息表" :visible.sync="outerVisible">
        <el-form class="form">
          <el-form-item class="item" label="地块号" :label-width="formLabelWidth">
            <el-input v-model="addMes.areaId" class="in" autocomplete="off" />
          </el-form-item>
          <div style="margin-left:52px;margin-bottom:24px">
            <label style="height: 36px;line-height: 36px;padding: 0 12px 0 0;">产品名称</label>
            <el-select v-model="addMes.productId" class="sel2" placeholder="请选择" style="width: 186px;">
              <el-option v-for="item in allProduct" :key="item.product_id" :label="item.product_name"
                :value="item.product_id" />
            </el-select>
          </div>
          <div style="margin-left:52px">
            <label style="height: 36px;line-height: 36px;padding: 0 12px 0 0;">员工姓名</label>
            <el-select v-model="addMes.employeeId" class="sel2" placeholder="请选择" style="width: 186px;">
              <el-option v-for="item in allEmployee" :key="item.employee_id" :label="item.employee_name"
                :value="item.employee_id" />
            </el-select>
          </div>
          <el-form-item class="item" label="种植方式" :label-width="formLabelWidth">
            <el-select v-model="addMes.plantMethod">
              <el-option v-for="item in plantTypeOption" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item class="item" label="种植时间" :label-width="formLabelWidth">
            <el-date-picker v-model="addMes.plantTime" type="datetime" class="in" autocomplete="off" placeholder="种植时间"
              value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss" />
          </el-form-item>
          <el-form-item class="item" label="种植规模（亩）" :label-width="formLabelWidth">
            <el-input-number v-model="addMes.plantScale" class="in" autocomplete="off" />
          </el-form-item>
          <el-form-item class="item" label="备注" :label-width="formLabelWidth">
            <el-input v-model="addMes.remark" class="in" autocomplete="off" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="outerVisible = false">取 消</el-button>
          <el-button type="primary" @click="addDri()">确 定</el-button>
        </div>
      </el-dialog>

      <el-table :data="mes" type="" style="width: 100%">
        <el-table-column prop="areaId" label="地块号" />
        <el-table-column prop="id" label="种植批次" width="180" />
        <el-table-column prop="productName" label="产品名称" />
        <el-table-column prop="employeeName" label="员工姓名" />
        <el-table-column prop="plantMethod" label="种植方式" />
        <el-table-column prop="plantScale" label="种植规模（亩）" />
        <el-table-column prop="plantTime" label="种植时间" />
        <el-table-column prop="remark" label="状态">
          <template #default="scope">
            <el-tag v-if="!scope.row.harvestId" color="#FFB300" style="color:white">未采摘</el-tag>
            <el-tag v-else color="green" style="color:white">已采摘</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" />
        <el-table-column fixed="right" label="操作" width="240">
          <template slot-scope="scope">
            <el-button type="text" style="color:green"
              @click="openAgriculturalControlForm(mes[scope.$index])" v-if="!scope.row.harvestId">施药</el-button>
            <el-button type="text" style="color:#FFB300"
              @click="openFertilizationForm(mes[scope.$index])" v-if="!scope.row.harvestId">施肥</el-button>
              <el-button type="text" style="color:blue" @click="openHarvestForm(scope.row)" v-if="!scope.row.harvestId">采摘</el-button>
            <el-button type="text" @click="changeMsg(mes[scope.$index],scope.$index)">修改</el-button>
            <el-button type="text" style="color:red" @click="mes[scope.$index].isShowDel = true">删除</el-button>

            <el-dialog :modal-append-to-body="false" title="提示" :visible.sync="mes[scope.$index].isShowDel" width="30%">
              <span>确认要删除此条信息吗？</span>
              <span slot="footer" class="dialog-footer">
                <el-button @click="mes[scope.$index].isShowDel = false">取 消</el-button>
                <el-button type="primary" @click="driveDel(scope.$index)">确 定</el-button>
              </span>
            </el-dialog>

            <el-dialog :modal-append-to-body="false" title="修改信息" :visible.sync="mes[scope.$index].isShow"
              :before-close="handleClose">
              <el-form class="form">
                <el-form-item class="item" label="地块号" :label-width="formLabelWidth">
                  <el-input v-model="mes[scope.$index].areaId" autocomplete="off" disabled/>
                </el-form-item>
                <el-form-item class="item" label="产品名称" :label-width="formLabelWidth">
                  <el-input v-model="mes[scope.$index].productName" autocomplete="off" disabled />
                </el-form-item>
                <el-form-item class="item" label="种植规模（亩）" :label-width="formLabelWidth">
                  <el-input-number v-model="mes[scope.$index].plantScale" autocomplete="off" />
                </el-form-item>
                <div style="margin-left:52px">
                  <label style="height: 36px;line-height: 36px;padding: 0 12px 0 0;">员工姓名</label>
                  <el-select v-model="mes[scope.$index].employeeId" class="sel2" placeholder="请选择"
                    style="width: 186px;">
                    <el-option v-for="item in allEmployee" :key="item.employee_id" :label="item.employee_name"
                      :value="item.employee_id" />
                  </el-select>
                </div>
                <el-form-item class="item" label="种植方式" :label-width="formLabelWidth">
                  <el-select v-model="mes[scope.$index].plantMethod">
                    <el-option v-for="item in plantTypeOption" :key="item.value" :label="item.label"
                      :value="item.value"> </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item class="item" label="种植时间" :label-width="formLabelWidth">
                  <el-date-picker v-model="mes[scope.$index].plantTime" type="datetime" class="in" autocomplete="off"
                    placeholder="种植时间" value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss" />
                </el-form-item>
                <el-form-item class="item" label="备注" :label-width="formLabelWidth">
                  <el-input v-model="mes[scope.$index].remark" autocomplete="off" type="textarea"
                    style="width: 350px;" />
                </el-form-item>
              </el-form>

              <div slot="footer" class="dialog-footer">
                <el-button @click="cancelChangeMsg(scope.$index)">取 消</el-button>
                <el-button type="primary" @click="changeInspectionForm(scope.$index,mes[scope.$index])">确 定</el-button>
              </div>

            </el-dialog>
          </template>
        </el-table-column>
      </el-table>
      <div class="page">
        <el-pagination :page-size="5" layout="prev, pager, next, jumper" :total="total" :current-page="pageNum"
          @current-change="handleCurrentChange" />
      </div>
    </div>
    <FertiliztionForm ref="fertiliztionForm" @refresh="load" />
    <AgriculturalControlForm ref="agriculturalControlForm" @refresh="load" />
    <HarvestForm ref="harvestForm" @refresh="load"/>
  </div>
</template>

<script>
import { plantTypeList } from "@/config/dict/trace"
import request from '../../../utils/request'
import FertiliztionForm from "./components/fertiliztionForm"
import AgriculturalControlForm from "./components/agriculturalControlForm"
import HarvestForm from "../productionBase/components/harvestForm.vue"
export default {
  name: 'FarmlandSelection',
  components: { FertiliztionForm, AgriculturalControlForm,HarvestForm },
  data () {
    return {
      mes: [],
      firstMes: [],
      allMes: [],
      index: null,
      dialogTableVisible: false,
      formLabelWidth: '120px',
      addMes: {},
      dialogFormVisible: false,
      outerVisible: false,
      pageSize: 5,
      pageNum: 1,
      deliverPageNum: 1,
      deliverPageSize: null,
      select: '',
      searchInf: '',
      searchInput: '',
      total: 0,
      allEmployee: [],
      allProduct: [],
      searchForm: {},
      plantTypeOption: plantTypeList
    }
  },
  async mounted () {
    this.load()
    this.getEmployee()
    this.getProduct()
  },
  methods: {
    async load () {
      await request({
        method: 'post',
        url: `/plant/plt/${this.pageNum}/${this.pageSize}`,
        data: this.searchForm
      }).then((response) => {
        this.mes = response.data.records
        for (let i = 0; i < this.mes.length; i++) {
          this.$set(this.mes[i], 'isShow', false)
          this.$set(this.mes[i], 'isShowDel', false)
        }
        this.total = response.data.total
        console.log(this.mes, 'this.mes');
      })
    },
    async getEmployee () {
      await request({
        method: 'get',
        url: '/plant/employee/getAll'
      }).then((response) => {
        this.allEmployee = JSON.parse(JSON.stringify(response.data))
      })
    },
    async getProduct () {
      await request({
        method: 'get',
        url: '/plant/product/getAll'
      }).then((response) => {
        this.allProduct = JSON.parse(JSON.stringify(response.data))
      })
    },
    changeMsg (mesIndex, index) {
      mesIndex.isShow = true
      this.firstMes = JSON.parse(JSON.stringify(this.mes))[index]
      this.index = index
    },

    async changeInspectionForm (index, mes) {
      var changMes = JSON.parse(JSON.stringify(this.mes))[index]
      for (let i = 0; i < this.allEmployee.length; i++) {
        const e = this.allEmployee[i]
        if (e.employee_id == changMes.employeeId) {
          changMes.employeeName = e.employee_name
        }
      }
      const newChangMes = {
        employeeId: changMes.employeeId,
        employeeName: changMes.employeeName,
        plantMethod: changMes.plantMethod,
        plantTime: changMes.plantTime,
        id: changMes.id,
        productId: changMes.productId,
        productName: changMes.productName,
        remark: changMes.remark,
        areaId: changMes.areaId,
        plantScale:changMes.plantScale
      }
      await request({
        method: 'put',
        url: '/plant/plt/' + mes.id,
        data: newChangMes
      }).then(response => {
        if (response.statusCode == 20000) {
          this.load()
          this.$message({
            message: '修改成功',
            type: 'success'
          })
        } else {
          this.$message({
            message: '发生错误，修改失败',
            type: 'warning'
          })
        }
        this.mes[index].isShow = false
      })
    },
    cancelChangeMsg (index) {
      this.$set(this.mes[index], 'isShow', false)
      this.$set(this.mes[index], 'isShowDel', false)
      this.mes[index] = JSON.parse(JSON.stringify(this.firstMes))
      this.load()
    },
    async driveDel (index) {
      await request({
        method: 'delete',
        url: '/plant/plt/' + this.mes[index].id
      }).then(response => {
        if (response.statusCode == 20000) {
          this.dialogFormVisible = false
          this.load()
          this.$message({
            message: '删除成功',
            type: 'success'
          })
        } else {
          this.$message({
            message: '发生错误，删除失败',
            type: 'warning'
          })
        }
      })
      this.mes[index].isShowDel = false
    },
    async addDri () {
      for (let i = 0; i < this.allProduct.length; i++) {
        const e = this.allProduct[i]
        if (e.product_id == this.addMes.productId) {
          this.addMes.productName = e.product_name
        }
      }
      for (let i = 0; i < this.allEmployee.length; i++) {
        const e = this.allEmployee[i]
        if (e.employee_id == this.addMes.employeeId) {
          this.addMes.employeeName = e.employee_name
        }
      }
      request({
        method: 'post',
        url: '/plant/plt',
        data: this.addMes
      }).then(response => {
        if (response.statusCode == 20000) {
          this.addMes = {}
          this.outerVisible = false;
          this.$message({
            message: '添加成功',
            type: 'success'
          })
          this.load()
        } else {
          this.$message({
            message: '发生错误，添加失败',
            type: 'warning'
          })
        }
      })
    },
    handleCurrentChange (val) {
      this.pageNum = val
      this.load()
    },
    searchMes () {
      if (this.searchInput) {
        if (this.select == 'productName') {
          this.searchForm = {
            productName: this.searchInput
          }
        } else if (this.select == 'employeeName') {
          this.searchForm = {
            employeeName: this.searchInput
          }
        } else if (this.select == 'plantMethod') {
          this.searchForm = {
            plantMethod: this.searchInput
          }
        }
      } else {
        this.searchForm = {}
      }
      this.load()
    },
    handleClose (done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
          this.addMes = {}
          this.cancelChangeMsg(this.index)
        })
        .catch(_ => { })
    },
    openAgriculturalControlForm (data) {
      this.$refs.agriculturalControlForm.init(data)
    },
    openFertilizationForm (data) {
      this.$refs.fertiliztionForm.init(data)
    },
    openHarvestForm(data){
      this.$refs.harvestForm.init(null,data)
    }
  }
}
</script>

<style lang="scss" scoped>
.header {
  width: 100%;
  height: 350px;
  display: flex;
  margin-bottom: 20px;
  justify-content: space-between;
}

.form {
  display: flex;
  flex-wrap: wrap;
}

.sel {
  width: 360px;
  display: flex;
  height: 50px;
  justify-content: flex-end;
  align-content: center;
}

.sel2 {
  width: 240px;
}

.page {
  width: 100%;
  display: flex;
  justify-content: right;
}

.imgDri {
  height: 300px;
  width: 400px;
}

.w1 {
  height: 80px;
  font-size: 25px;
  font-weight: 350;
}

.w2 {
  height: 50px;
  font-size: 15px;
  font-weight: 250;
}

.searchHead {
  display: flex;
  justify-content: space-between;
}

.searchIuput {
  width: 350px;
}

.sel3 {
  width: 120px;
}
</style>

